package com.zh.chat.gui.tree;

import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.border.EmptyBorder;
import javax.swing.tree.DefaultTreeModel;

import com.zh.chat.controller.ClientContext;


public class FriendsPanel extends JPanel {

	/**
	 * 好友列表JPanel
	 */
	private static final long serialVersionUID = -8879025096846649809L;
	private ClientContext clientContext = null;
	
	/**
	 * 为好友列表UI中的监听器服务，一旦有双击好友的行文立即通知控制器，做出聊天初始化操作
	 * @param clientContext
	 */
	public void setClientContext(ClientContext clientContext) {
		this.clientContext = clientContext;
	}
	// 滚动条容器
	private JTree jtree;
	private DefaultTreeModel treeModel = null;
	private IconTreeNode nodeRoot = new IconTreeNode("all");
	private IconNodeRenderer INRender = null;

	public JTree getJtree() {
		return jtree;
	}

	public void setJtree(JTree jtree) {
		this.jtree = jtree;
	}
	
	public DefaultTreeModel getTreeModel() {
		return treeModel;
	}

	public FriendsPanel() {
		init();
	}
	
	private void init() {
		this.setLayout(new BorderLayout());
		// 下面构造JTree
		jtree = new JTree(nodeRoot);
		// 设置根Root不可见
		jtree.setRootVisible(false);
		// 设置渲染器
		this.INRender = new IconNodeRenderer();
		jtree.setCellRenderer(INRender);
		jtree.setRowHeight(40);
		// 下面这一行获取JTree的模型，为了在JButton中实现动态添加而预设的，也可以在JButton的事件响应中再写
		treeModel = (DefaultTreeModel) jtree.getModel();
		this.setBorder(new EmptyBorder(0, 10, 0, 0));
		this.add(jtree, BorderLayout.CENTER);
		jtree.addMouseListener(new MouseAdapter() {
			private Object lastObject = null;
			private long lastClickTime = 0;
			@Override
			public void mouseClicked(MouseEvent event) {
				super.mouseClicked(event);
				try{
				JTree tree = null;
				Object obj = event.getSource();
				if(obj instanceof JTree){
					tree = (JTree)obj;
					long current = System.currentTimeMillis();
					if(lastObject==null || (current-lastClickTime)>500){
						lastClickTime=System.currentTimeMillis();
						lastObject = tree.getSelectionPath().getLastPathComponent();
					}else{
						Object currentObject = tree.getSelectionPath().getLastPathComponent();
						if(lastObject==currentObject && currentObject!=null){
							IconTreeNode node = (IconTreeNode) currentObject;
							if(node.getFriend()!=null){
								clientContext.readyToChat(node.getFriend());
							}
						}
					}
				}
				}catch(Exception e){}
			}
		});
	}
}